package com.whz.workmanageol.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 多个文件打包成为zip文件下载到本地
 */
public class MutilFilesDownload {

    private static Logger logger = LoggerFactory.getLogger(MutilFilesDownload.class);
    public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException{
        try {
            int fileSize = files.size();
            // 压缩列表中的文件
            for(int i = 0; i < fileSize; i++) {
                File file = files.get(i);
                zipFile(file, outputStream);
            }
        } catch (IOException e) {
            throw e;
        }

    }
    public static void zipFile(File inputFile, ZipOutputStream outputStream) throws IOException {
        if(inputFile.exists()) {
            if(inputFile.isFile()) {
                FileInputStream inputStream = new FileInputStream(inputFile);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                ZipEntry entry = new ZipEntry(inputFile.getName());
                outputStream.putNextEntry(entry);

                final int MAX_BYTE = 10 * 1024 * 1024;
                // 文件总字节数
                long streamTotal = 0;
                //
                int streamNum = 0;
                //
                int leaveByte = 0;
                byte[] inOutbyte;

                streamTotal = bufferedInputStream.available();
                streamNum = (int) Math.floor(streamTotal / MAX_BYTE);
                leaveByte = (int) (streamTotal % MAX_BYTE);

                if(streamNum > 0) {
                    for (int j = 0; j < streamNum; ++j) {
                        inOutbyte = new byte[MAX_BYTE];
                        // 读入流 保存在byte数组
                        bufferedInputStream.read(inOutbyte, 0, MAX_BYTE);
                        // 写出流
                        outputStream.write(inOutbyte, 0, MAX_BYTE);
                    }
                }
                // 写出剩下的流数据
                inOutbyte = new byte[leaveByte];
                bufferedInputStream.read(inOutbyte, 0, leaveByte);
                outputStream.write(inOutbyte);
                outputStream.closeEntry();
                bufferedInputStream.close();
                inputStream.close();
            }
        }
    }

    public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {

        try(BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
            int fisSize = fis.available();
            byte[] buffer = new byte[fisSize];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(file.getName().getBytes(StandardCharsets.UTF_8),
                            StandardCharsets.ISO_8859_1));
            toClient.write(buffer);
            toClient.flush();
            if(isDelete) {
                file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 非递归遍历文件夹
    public static List<File> traveseFolder(String dirPath) {
        List<File> workList = new ArrayList<>();
        File dirFile = new File(dirPath);
        if(dirFile.exists()) {
            LinkedList<File> fileList = new LinkedList<>();
            File[] files = dirFile.listFiles();
            for(File file : files) {
                if(file.isDirectory()) {
                    fileList.add(file);
                } else {
                    if(!file.getName().endsWith(".zip"))
                    workList.add(file);
                }
            }
            File tempFile;
            while (!fileList.isEmpty()) {
                tempFile = fileList.removeFirst();
                File[] tempFiles = tempFile.listFiles();
                for (File file : tempFiles) {
                    if(file.isDirectory()) {
                        fileList.add(file);
                    } else {
                        if(!file.getName().endsWith(".zip"))
                        workList.add(file);
                    }
                }
            }
        }
        return workList;
    }
}
